/*
缓存加载函数
cacheLen：最多缓存多少个接口
id：唯一值
name：方法名
syncFunc：加载函数
 */
// 缓存最近的20个接口
import localData from './localData'
import _ from 'lodash'
const methodCacheArr = []
let cacheLen = 20
export function initCache (name) {
  const arr = localData('queryStore')
  if (_.isArray(arr)) {
    arr.forEach(function (item) {
      methodCacheArr.push(item)
    })
    cacheLen = arr.length + 20
  }
}

function getCacheIndex (val, key) {
  let has = -1
  for (let i = methodCacheArr.length - 1; i >= 0; i--) {
    if (val === methodCacheArr[i][key]) {
      has = i
      break
    }
  }
  return has
}

export function getCache (name) {
  const has = getCacheIndex(name, 'name')
  if (has > -1) {
    return methodCacheArr[has].res
  } else {
    return null
  }
}
export function getCacheData (name) {
  const has = getCacheIndex(name, 'name')
  if (has > -1) {
    return methodCacheArr[has].res.data
  } else {
    return null
  }
}
export function delCache (name) {
  const has = getCacheIndex(name, 'name')
  if (has > -1) {
    const store = methodCacheArr[has].store
    methodCacheArr.splice(has, 1)
    if (store) {
      updateCache()
    }
  }
}
export function updateCache () {
  const arr = methodCacheArr.filter(function (item) {
    return item.store
  })
  localData('queryStore', arr)
}
export async function limitCache ({ id, name, useCache, store, queryNoError }, syncFunc) {
  const has = getCacheIndex(id, 'id')

  if (useCache && has > -1) {
    if (typeof useCache !== 'number') {
      useCache = 300
    }
    if (useCache * 1000 + methodCacheArr[has].time > +new Date()) {
      return methodCacheArr[has].res
    }
  }
  const res = await syncFunc()
  // 更新缓存
  if (res && res.flag === 'S') {
    if (has > -1) {
      methodCacheArr.splice(has, 1)
    }
    methodCacheArr.push({
      id: id,
      store: store,
      name: name,
      time: +new Date(),
      res: res
    })
    if (methodCacheArr.length > cacheLen) {
      methodCacheArr.splice(0, 1)
    }
    if (store) {
      updateCache()
    }
  } else if (has > -1 && queryNoError) {
    // 兼容查询失败的情况
    return methodCacheArr[has].res
  }
  return res
}
